package edu.rjxy.xjdx.emps.dao;

import edu.rjxy.xjdx.emps.common.domain.Employee;
import edu.rjxy.xjdx.emps.common.utils.CountVo;
import edu.rjxy.xjdx.emps.common.utils.MyDbUtil;
import edu.rjxy.xjdx.emps.common.utils.PageInfo;

import java.util.ArrayList;
import java.util.List;

public class EmployeeDaoImpl implements EmployeeDao {
    @Override
    public List<Employee> selectAllEmployee() {
        String sql = " select * from employee ";
        return MyDbUtil.executeQuery(Employee.class,sql);
    }

    @Override
    public PageInfo<Employee> selectEmpByPage(int pageNo, int pageSize) {
        String sql = " select * from employee limit ?,? ";
        List<Employee> list = MyDbUtil.executeQuery(Employee.class, sql, (pageNo - 1) * pageSize, pageSize);
        return new PageInfo<>(pageNo,pageSize,getCount(),list);
    }

    @Override
    public void deleteEmployeeById(int id) {
        String sql = " delete from employee where id = ? ";
        MyDbUtil.executeUpdate(sql,id);
    }

    @Override
    public int insertEmployee(Employee employee) {
        String sql = " insert into employee(name,personNumber,sex) values(?,?,?) " ;
        return MyDbUtil.executeUpdate(sql,employee.getName(),employee.getPersonNumber(),employee.getSex());
    }

    private int getCount(){
        String sql = " select count(id) 'count' from employee  ";
       // return MyDbUtil.
//         加点文采
        List<CountVo> countVos = MyDbUtil.executeQuery(CountVo.class, sql);
        CountVo countVo = (countVos!=null && countVos.size()>0)?countVos.get(0):null;
        return (int)(countVo!=null?countVo.getCount():0);
    }


    public static void main(String[] args) {
        int count = new EmployeeDaoImpl().getCount();
        System.out.println(count);
    }

    @Override
    public Employee selectEmployeeById(int id) {
        String sql = " select * from employee where id = ? ";
        List<Employee> employees = MyDbUtil.executeQuery(Employee.class, sql, id);
        return (employees.size()>0?employees.get(0):null);
    }

    @Override
    public int updateEmployee(Employee employee) {
        String sql = " update  employee set name = ?,personNumber = ?,sex=?  where id = ? ";
        return MyDbUtil.executeUpdate(sql,employee.getName(),employee.getPersonNumber(),employee.getSex(),employee.getId());
    }
}
